<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="utf-8">
    <title>密钥管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/static/plugin/layui/css/layui.css}" media="all">
</head>
<body>
<div class="searchTable">
    <div class="layui-inline">
        <input class="layui-input" name="s_voucherName" id="s_voucherName" autocomplete="off" placeholder="凭证组名称">
    </div>
    <div class="layui-inline">
        <input class="layui-input" name="s_secretKeyName" id="s_secretKeyName" autocomplete="off" placeholder="密钥名称">
    </div>
    <div class="layui-inline">
        <input class="layui-input" name="s_appKey" id="s_appKey" autocomplete="off" placeholder="appKey">
    </div>
    <div class="layui-inline">
        <input class="layui-input" name="s_appSecret" id="s_appSecret" autocomplete="off" placeholder="appSecret">
    </div>
    <button type="button" id="searchBtn" class="layui-btn" data-type="reload">搜索</button>
</div>

<!--二维列表-->
<table class="layui-hide" id="MangeSecretKeyTable" lay-filter="MangeSecretKeyTable"></table>

<input type="text" id="ctx" hidden="hidden" th:value="${#request.getContextPath()}">

<!--新增/编辑表单-->
<div class="layui-row" id="editForm" style="display:none;">
    <div class="layui-col-md10">
        <form class="layui-form layui-from-pane" action="" style="margin-top:20px; margin-right: 20px">
            <!--主键-->
            <input type="text" id="id" name="id" hidden="hidden">
            <div class="layui-form-item">
                <label class="layui-form-label">所属凭证组</label>
                <div class="layui-input-block">
                    <select id="voucherIdSelect" name="voucherId" lay-verify="required">

                    </select>
                    <div class="layui-unselect layui-form-select">
                        <div class="layui-select-title">
                            <input type="text" placeholder="请选择" value="" readonly=""
                                   class="layui-input layui-unselect">
                            <i class="layui-edge"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">秘钥名称</label>
                <div class="layui-input-block">
                    <input type="text" id="secretKeyName" name="secretKeyName" required lay-verify="required"
                           autocomplete="off"
                           placeholder="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">appKey</label>
                <div class="layui-input-block">
                    <input type="text" id="appKey" name="appKey" required lay-verify="required"
                           autocomplete="off"
                           placeholder="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">appSecret</label>
                <div class="layui-input-block">
                    <input type="text" id="appSecret" name="appSecret" required lay-verify="required"
                           autocomplete="off"
                           placeholder="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">摄像头限制数量</label>
                <div class="layui-input-block">
                    <input type="text" id="cameraLimitNum" name="cameraLimitNum" required lay-verify="required"
                           autocomplete="off"
                           placeholder="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">采集器限制数量</label>
                <div class="layui-input-block">
                    <input type="text" id="collectLimitNum" name="collectLimitNum" required lay-verify="required"
                           autocomplete="off"
                           placeholder="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" style="margin-top:40px">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="confirm">保存</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="back">取消</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/html" id="userToolBar">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-sm" lay-event="add">新增秘钥</button>
    </div>
</script>

<script type="text/html" id="tbBar">
    <!-- 编辑 -->
    <i style="font-size: 24px; color: #298f83;" class="layui-icon layui-icon-edit " lay-event="modify"
       shiro:hasPermission="/manageVoucher/addModify"></i>
    <!--删除-->
    <i style="font-size: 24px; color: #f4577b;" class="layui-icon layui-icon-delete " lay-event="remove"
       shiro:hasPermission="/manageVoucher/delete"></i>
</script>

<script th:src="@{/static/js/jquery.min.js}" charset="utf-8"></script>
<script th:src="@{/static/plugin/layui/layui.js}" charset="utf-8"></script>
<script th:src="@{/static/js/app.js}" charset="utf-8"></script>
<script src="/static/js/whysu.js" th:src="@{/static/js/whysu.js}"></script>

<!--序号自增-->
<script type="text/html" id="xuhao">
    {{d.LAY_TABLE_INDEX+1}}
</script>

<script>
    layui.use(['jquery', 'table', 'layer'], function () {
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;
        // 所有的凭证组名称列表
        var voucherNameList = getAllVoucherNameList();

        // 获取所有的凭证组列表
        function getAllVoucherNameList() {
            var list;
            $.ajax({
                url: ctx + '/manageVoucher/getAllVoucherNameList',
                type: "POST",
                async: false, // 同步
                contentType: "application/json",
                dataType: "json",
                data: requestDTO(),
                success: function (data) {
                    if (data.result.code == 200) {
                        list = data.body;
                    }
                }
            });
            return list;
        }

        // 添加凭证组的下拉框
        function addVoucherOption(target, voucherNameList, flag) {
            console.log(voucherNameList);
            // 先清空掉之前的选项
            target.find("option").remove();
            // 如果为true则显示请选择选项
            if (flag) {
                target.append(new Option());
            }
            if (typeof voucherNameList != "undefined") {
                // 遍历集合，赋值option
                $.each(voucherNameList, function (index, item) {
                    target.append(new Option(item.voucherName, item.id));
                });
            }
        }

        // 二维表格
        table.render({
            elem: '#MangeSecretKeyTable'
            , url: ctx + '/manageSecretKey/getPage'
            , method: 'post'
            , contentType: 'application/json'
            , toolbar: '#userToolBar' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: false //去掉右上角的打印等按钮
            , title: 'MangeSecretKeyTable'
            , loading: true //显示加载条
            , cols: [
                [
                    {title: '序号', templet: '#xuhao', align: 'center'},
                    {field: 'id', title: 'ID', hide: true},
                    {field: 'secretKeyName', title: '秘钥名称', align: 'center'},
                    {field: 'voucherId', title: '凭证组id', hide: true},
                    {field: 'voucherName', title: '所属凭证组', align: 'center'},
                    {field: 'cameraLimitNum', title: '摄像头限制数量', align: 'center'},
                    {field: 'collectLimitNum', title: '采集器限制数量', align: 'center'},
                    {field: 'createBy', title: '创建者', align: 'center'},
                    {field: 'updateBy', title: '更新者', align: 'center'},
                    {
                        field: 'createTime', title: '创建时间', align: 'center',
                        templet: function (d) {
                            if (d.createTime == null) {
                                return "";
                            } else {
                                return layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss');
                            }
                        }
                    },
                    {
                        field: 'updateTime', title: '更新时间', align: 'center',
                        templet: function (d) {
                            if (d.updateTime == null) {
                                return "";
                            } else {
                                return layui.util.toDateString(d.updateTime, 'yyyy-MM-dd HH:mm:ss');
                            }
                        }
                    },
                    {fixed: 'right', title: '操作', toolbar: '#tbBar'}
                ]
            ]
            , page: true
            , request: {
                pageName: 'pageNum'//页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": res.body.totalSize, //解析数据长度
                    "data": res.body.list //解析数据列表
                };
            }

        });

        /*重载*/
        var $ = layui.$, active = {
            reload: function () {
                var queryWhere = {};
                // 凭证组名称
                var voucherName$_ = $('#s_voucherName');
                if (voucherName$_.val() != '') {
                    queryWhere['queryVoucherName'] = voucherName$_.val();
                }
                // 秘钥名称
                var secretKeyName$_ = $('#s_secretKeyName');
                if (secretKeyName$_.val() != '') {
                    queryWhere['querySecretKeyName'] = secretKeyName$_.val();
                }
                // appKey
                var appKey$_ = $('#s_appKey');
                if (appKey$_.val() != '') {
                    queryWhere['queryAppKey'] = appKey$_.val();
                }
                // appSecret
                var appSecret$_ = $('#s_appSecret');
                if (appSecret$_.val() != '') {
                    queryWhere['queryAppSecret'] = appSecret$_.val();
                }
                //执行重载
                table.reload('MangeSecretKeyTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: queryWhere
                    , done: function (res, curr, count) {
                        this.where = {};
                    }
                }, 'data');
            }
        };

        /*搜索*/
        $('#searchBtn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        /*新增、修改*/
        form.on('submit(confirm)', function (massage) {
            $.ajax({
                url: ctx + '/manageSecretKey/addModify',
                type: "POST",
                contentType: "application/json",
                dataType: "json",
                data: requestDTO(massage.field),
                beforeSend: function () {
                    this.layerIndex = showLoad();
                },
                complete: function () {
                    closeLoad(this.layerIndex);
                },
                success: function (data) {
                    if (data.result.code == 200) {
                        // 关闭所有弹窗
                        layer.closeAll();
                        // 操作成功
                        layer.msg("操作成功", {
                            time: 1000
                        });
                        // 重新加载表格
                        table.reload('MangeSecretKeyTable');
                    } else {
                        layer.msg(data.result.message);
                    }
                },
                error: function (result) {
                    layer.msg("请求失败！");
                }
            });

            return false;
        });

        //头工具栏事件
        table.on('toolbar(MangeSecretKeyTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                //自定义头工具栏右侧图标 - 提示
                case 'add': {
                    layer.open({
                        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        type: 1,
                        title: "新增",
                        area: ['60%', '80%'],
                        content: $("#editForm")//引用的弹出层的页面层的方式加载修改界面表单
                    });
                    setFormValue(null, null);
                    break;
                }
                default:
                    break;
            }
            ;
        });

        //监听弹出框表单提交，massage是修改界面的表单数据'submit(confirm),是修改按钮的绑定

        //监听行工具事件
        table.on('tool(MangeSecretKeyTable)', function (obj) {
            var data = obj.data;
            // console.log(obj)
            if (obj.event === 'remove') {
                layer.confirm('确定删除该秘钥？', function (index) {
                    $.ajax({
                        type: "POST",
                        url: ctx + "/manageSecretKey/delete",
                        contentType: "application/json",
                        dataType: "json",
                        data: requestDTO(data.id),
                        beforeSend: function () {
                            this.layerIndex = showLoad();
                        },
                        complete: function () {
                            closeLoad(this.layerIndex);
                        },
                        success: function (response) {
                            if (response.result.code == 200) {
                                layer.msg("操作成功", {
                                    timeout: 1000
                                }, function () {
                                    // 关闭窗口
                                    layer.close(index);
                                });
                                //执行重载
                                var queryWhere = {};
                                table.reload('MangeSecretKeyTable', {
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    }
                                    , where: queryWhere
                                    , done: function (res, curr, count) {
                                        this.where = {};
                                    }
                                }, 'data');
                            } else {
                                layer.msg(response.result.message)
                            }
                        },
                        error: function (e) {
                            layer.msg("删除请求失败！");
                        }
                    });
                });
            } else if (obj.event === 'modify') {
                //iframe层-父子操作
                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "修改",
                    area: ['60%', '80%'],
                    content: $("#editForm")//引用的弹出层的页面层的方式加载修改界面表单
                });
                setFormValue(obj, data);
            }
        });

        // 填充form
        function setFormValue(obj, data) {
            // 凭证组下拉框
            var target = $("#voucherIdSelect");
            addVoucherOption(target, voucherNameList);

            if (data != null) {
                $("#id").val(data.id);
                $("#secretKeyName").val(data.secretKeyName);
                $("#appKey").val(data.appKey);
                $("#appSecret").val(data.appSecret);
                $("#cameraLimitNum").val(data.cameraLimitNum);
                $("#collectLimitNum").val(data.collectLimitNum);
                // 选中凭证组下拉框
                target.val(data.voucherId);
            } else {
                // 秘钥主键id
                $("#id").val('');
                $("#secretKeyName").val('');
                $("#appKey").val('');
                $("#appSecret").val('');
                $("#cameraLimitNum").val('');
                $("#collectLimitNum").val('');
            }
            layui.form.render();
        }

        $("#back").on('click', function () {
            layer.closeAll();
        });

    });
</script>

</body>
</html>